package com.hy.frame.recycler;

import android.annotation.SuppressLint;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 网格装饰器
 * 网格orientation会出现均分
 */
public class GridItemDecoration extends LinearItemDecoration {

    private int verticalDivider;
    private boolean stretch;

    public GridItemDecoration(int divider) {
        super(divider);
    }

    public GridItemDecoration(int divider, int color) {
        super(divider, color);
    }

    public GridItemDecoration(int divider, @Nullable Drawable drawable) {
        super(divider, drawable);
    }
//    public GridItemDecoration(RecyclerView rcyList, int divider) {
//        this(rcyList, divider, 0);
//    }

//    public GridItemDecoration(RecyclerView rcyList, int divider, int color) {
//        super(rcyList, divider, color);
//        init();
//    }
//
//    public GridItemDecoration(RecyclerView rcyList, int divider, Drawable drawable) {
//        super(rcyList, divider, drawable);
//        init();
//    }

    public GridItemDecoration setVerticalDivider(int divider) {
        this.verticalDivider = divider;
        return this;
    }

    /**
     * 分割线穿透模式开关
     *
     * @param stretch 开关
     */
    public GridItemDecoration setStretch(boolean stretch) {
        this.stretch = stretch;
        return this;
    }

    public boolean isStretch() {
        return stretch;
    }

    public int getVerticalDivider() {
        return verticalDivider;
    }

//    @Override
//    public GridItemDecoration build() {
//        if (spanCount > 1) {
//            if (orientation == LinearLayoutManager.VERTICAL && paddingLeft > 0 && rcyList.getPaddingLeft() == 0) {
//                rcyList.setPadding(paddingLeft, rcyList.getPaddingTop(), rcyList.getPaddingTop(), rcyList.getPaddingBottom());
//            } else if (orientation == LinearLayoutManager.HORIZONTAL && paddingTop > 0 && rcyList.getPaddingTop() == 0) {
//                rcyList.setPadding(rcyList.getPaddingLeft(), paddingTop, rcyList.getPaddingTop(), rcyList.getPaddingBottom());
//            }
//        }
//        return this;
//    }

    @SuppressLint("NotifyDataSetChanged")
    protected boolean resetRecyclerViewPadding(@NonNull RecyclerView parent, int orientation) {
        if (orientation == RecyclerView.VERTICAL) {
            if (parent.getPaddingLeft() != getPadding().left || parent.getPaddingTop() != 0 || parent.getPaddingRight() != getPadding().right || parent.getPaddingBottom() != 0) {
                parent.setPadding(getPadding().left, 0, getPadding().right, 0);
                RecyclerView.Adapter<?> adapter = parent.getAdapter();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                return false;
            }
        } else {
            if (parent.getPaddingLeft() != 0 || parent.getPaddingTop() != getPadding().top || parent.getPaddingRight() != 0 || parent.getPaddingBottom() != getPadding().bottom) {
                parent.setPadding(0, getPadding().top, 0, getPadding().bottom);
                RecyclerView.Adapter<?> adapter = parent.getAdapter();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
                return false;
            }

        }
        return true;
    }

    @Override
    protected void drawDivider(@NonNull Canvas canvas, @NonNull RecyclerView parent) {
        Log.d("GridItemDecoration", "drawDivider: ");
        RecyclerView.Adapter<?> adapter = parent.getAdapter();
        RecyclerView.LayoutManager manager = parent.getLayoutManager();
        if (adapter == null || !(manager instanceof GridLayoutManager)) return;
        int spanCount = ((GridLayoutManager) manager).getSpanCount();
        int orientation = ((GridLayoutManager) manager).getOrientation();
        if (spanCount <= 1) {
            super.drawDivider(canvas, parent);
            return;
        }
        if (!resetRecyclerViewPadding(parent, orientation)) {
            return;
        }
        if (getDivider() == 0 && getVerticalDivider() == 0) {
            return;
        }
        int count = adapter.getItemCount();
        int childCount = parent.getChildCount();
        int lastStretchRow = -1;
        int lastStretchColumn = -1;
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int viewAdapterPosition = params.getViewAdapterPosition();
            int viewType = adapter.getItemViewType(viewAdapterPosition);
            if (viewType != 0) continue; //为0时才绘制
            if (orientation == RecyclerView.VERTICAL) {
                int row = getRowNumber(viewAdapterPosition, spanCount);
                int column = getColumnNumber(viewAdapterPosition, spanCount);
                if (getDivider() != 0) {
                    //顶部分割线
                    if (isStartDivider() && row == 1) {
                        if (isStretch()) {
                            if (lastStretchRow != row) {
                                drawRectDivider(canvas, parent.getLeft() + getPadding().left, child.getTop() - getDivider(), parent.getRight() - getPadding().right, child.getTop());
                            }
                        } else {
                            drawRectDivider(canvas, child.getLeft(), child.getTop() - getDivider(), child.getRight(), child.getTop());
                        }
                    }
                    //底部分割线
                    if (isEndLine(viewAdapterPosition, spanCount, count)) {
                        if (!isEndDivider()) {
                            lastStretchRow = row;
                            continue;
                        }
                    }
                    if (isStretch()) {
                        if (lastStretchRow != row) {
                            drawRectDivider(canvas, parent.getLeft() + getPadding().left, child.getBottom(), parent.getRight() - getPadding().right, child.getBottom() + getDivider());
                        }
                    } else {
                        drawRectDivider(canvas, child.getLeft(), child.getBottom(), child.getRight(), child.getBottom() + getDivider());
                    }
                    lastStretchRow = row;
                }
                if (getVerticalDivider() != 0) {
                    //右侧分割线
                    if (isStretch()) {
                        if (lastStretchColumn != column) {
                            drawRectDivider(canvas, child.getRight(), parent.getTop() + getPadding().top, child.getRight() + getVerticalDivider(), parent.getBottom() - getPadding().bottom);
                            lastStretchColumn = column;
                        }
                    } else {
                        drawRectDivider(canvas, child.getRight(), child.getTop(), child.getRight() + getVerticalDivider(), child.getBottom());
                    }
                }
            } else {
                int row = getColumnNumber(viewAdapterPosition, spanCount);
                int column = getRowNumber(viewAdapterPosition, spanCount);
                if (getDivider() != 0) {
                    //底部分割线
                    if (isStretch()) {
                        if (lastStretchRow != row) {
                            drawRectDivider(canvas, parent.getLeft() + getPadding().left, child.getBottom(), parent.getRight() - getPadding().right, child.getBottom() + getDivider());
                            lastStretchRow = row;
                        }
                    } else {
                        drawRectDivider(canvas, child.getLeft(), child.getBottom(), child.getRight(), child.getBottom() + getDivider());
                    }
                }
                if (getVerticalDivider() != 0) {
                    //左侧分割线
                    if (isStartDivider() && column == 1) {
                        if (isStretch()) {
                            if (lastStretchColumn != column) {
                                drawRectDivider(canvas, child.getLeft() - getVerticalDivider(), parent.getTop() + getPadding().top, child.getLeft(), parent.getBottom() - getPadding().bottom);
                            }
                        } else {
                            drawRectDivider(canvas, child.getLeft() - getVerticalDivider(), child.getTop(), child.getLeft(), child.getBottom());
                        }
                    }
                    //右侧分割线
                    if (isEndLine(viewAdapterPosition, spanCount, count)) {
                        if (!isEndDivider()) {
                            lastStretchColumn = column;
                            continue;
                        }
                    }
                    if (isStretch()) {
                        if (lastStretchColumn != column) {
                            drawRectDivider(canvas, child.getRight(), parent.getTop() + getPadding().top, child.getRight() + getVerticalDivider(), parent.getBottom() - getPadding().bottom);
                        }
                    } else {
                        drawRectDivider(canvas, child.getRight(), child.getTop(), child.getRight() + getVerticalDivider(), child.getBottom());
                    }
                    lastStretchColumn = column;
                }
            }
        }
    }


    @Override
    protected void configureItemOutRect(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent) {
        RecyclerView.Adapter<?> adapter = parent.getAdapter();
        RecyclerView.LayoutManager manager = parent.getLayoutManager();
        if (adapter == null || manager == null || (getDivider() == 0 && getVerticalDivider() == 0)) {
            outRect.set(0, 0, 0, 0);
            return;
        }
        if (!(manager instanceof GridLayoutManager)) {
            super.configureItemOutRect(outRect, view, parent);
            return;
        }
        int spanCount = ((GridLayoutManager) manager).getSpanCount();
        if (spanCount <= 1) {
            super.configureItemOutRect(outRect, view, parent);
            return;
        }
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
        int viewAdapterPosition = params.getViewAdapterPosition();
        int viewType = adapter.getItemViewType(viewAdapterPosition);
        if (!containsType(viewType)) { //包含的Item类型时才绘制
            outRect.set(0, 0, 0, 0);
            return;
        }
        int count = adapter.getItemCount();
        int left = 0;
        int top = 0;
        int right = 0;
        int bottom = 0;
        int orientation = ((GridLayoutManager) manager).getOrientation();
        if (orientation == RecyclerView.VERTICAL) {
            // 排列规则
            // 1 2 3
            // 4 5 6
            // 7 8
//            if ((viewAdapterPosition + 1) % spanCount == 1) {//当前行第一条
//                left = getPadding().left;
//            }
            if (viewAdapterPosition < spanCount) {//第一排
                top = getPadding().top;
                if (isStartDivider()) {//第一条顶部是否需要添加分割线
                    top += getDivider();
                }
            }
            right = getVerticalDivider();
            if (isEndLine(viewAdapterPosition, spanCount, count)) {//最后一排
                bottom = getPadding().bottom;
                if (isEndDivider()) {//最后一条底部是否需要添加分割线
                    bottom += getDivider();
                }
            } else {
                bottom = getDivider();
            }
        } else {
            // 排列规则
            // 1 4 7
            // 2 5 8
            // 3 6
            if (viewAdapterPosition < spanCount) {//当前行第一条
                left = getPadding().left;
                if (isStartDivider()) {
                    left += getVerticalDivider();
                }
            }
//            if ((viewAdapterPosition + 1) % spanCount == 1) {//第一排
//                top = getPadding().top;
//                if (isStartDivider()) {//第一条顶部是否需要添加分割线
//                    top += getDivider();
//                }
//            }
            if (isEndLine(viewAdapterPosition, spanCount, count)) {//当前行最右边
                right = getPadding().right;
                if (isEndDivider()) {
                    right += getVerticalDivider();
                }
            } else {
                right = getVerticalDivider();
            }
            bottom = getDivider();
//            if ((viewAdapterPosition + 1) == spanCount || (viewAdapterPosition + 1 == count)) {//最后一排
//                bottom = getPadding().bottom;
//                if (isEndDivider()) {//最后一条底部是否需要添加分割线
//                    bottom += getDivider();
//                }
//            } else {
//                bottom = getDivider();
//            }
        }

        outRect.set(left, top, right, bottom);
    }

    private int getRowNumber(int index, int spanCount) {
        int line = (index + 1) / spanCount;
        if ((index + 1) % spanCount > 0) {
            line += 1;
        }
        return line;
    }

    private int getColumnNumber(int index, int spanCount) {
        int column = (index + 1) % spanCount;
        if (column == 0) {
            column = spanCount;
        }
        return column;
    }

    /**
     * 是否是最后一排
     *
     * @param index 下标
     * @param count 总数
     */
    private boolean isEndLine(int index, int spanCount, int count) {
        if (count <= spanCount) return true; //不足一排
        int lines = count / spanCount;
        if (count % spanCount > 0)
            lines++;
        return lines == getRowNumber(index, spanCount);
    }
}
